package com.yupi.yupicturebackend.controller;

import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.dto.ai.AIGenerationConfig;
import com.yupi.yupicturebackend.model.dto.ai.AIGenerationResult;
import com.yupi.yupicturebackend.model.entity.AIGenerationTask;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.service.AIGenerationTaskService;
import com.yupi.yupicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * AI图片生成控制器
 *
 * @author yupi
 */
@Slf4j
@RestController
@RequestMapping("/ai/generation")
public class AIGenerationController {

    @Resource
    private AIGenerationTaskService aiGenerationTaskService;

    @Resource
    private UserService userService;

    /**
     * 创建AI图片生成任务
     *
     * @param request 生成请求
     * @param httpRequest HTTP请求
     * @return 任务ID
     */
    @PostMapping("/create")
    public BaseResponse<String> createGenerationTask(@RequestBody GenerationRequest request, 
                                                   HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getPrompt() == null || request.getPrompt().trim().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "提示词不能为空");
        
        User loginUser = userService.getLoginUser(httpRequest);
        AIGenerationConfig config = request.getConfig() != null ? request.getConfig() : new AIGenerationConfig();
        
        String taskId = aiGenerationTaskService.createGenerationTask(request.getPrompt(), config, loginUser.getId());
        
        return ResultUtils.success(taskId);
    }

    /**
     * 执行AI图片生成
     *
     * @param taskId 任务ID
     * @param httpRequest HTTP请求
     * @return 生成结果
     */
    @PostMapping("/execute/{taskId}")
    public BaseResponse<AIGenerationResult> executeGeneration(@PathVariable String taskId,
                                                            HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(taskId == null || taskId.trim().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "任务ID不能为空");
        
        User loginUser = userService.getLoginUser(httpRequest);
        AIGenerationResult result = aiGenerationTaskService.executeGeneration(taskId);
        
        ThrowUtils.throwIf(result == null, ErrorCode.OPERATION_ERROR, "生成任务执行失败");
        
        return ResultUtils.success(result);
    }

    /**
     * 获取用户生成任务列表
     *
     * @param limit 限制数量
     * @param httpRequest HTTP请求
     * @return 任务列表
     */
    @GetMapping("/tasks")
    public BaseResponse<List<AIGenerationTask>> getUserTasks(@RequestParam(defaultValue = "20") Integer limit,
                                                           HttpServletRequest httpRequest) {
        User loginUser = userService.getLoginUser(httpRequest);
        List<AIGenerationTask> tasks = aiGenerationTaskService.getUserTasks(loginUser.getId(), limit);
        
        return ResultUtils.success(tasks);
    }

    /**
     * 获取任务详情
     *
     * @param taskId 任务ID
     * @param httpRequest HTTP请求
     * @return 任务详情
     */
    @GetMapping("/task/{taskId}")
    public BaseResponse<AIGenerationTask> getTaskDetail(@PathVariable String taskId,
                                                      HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(taskId == null || taskId.trim().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "任务ID不能为空");
        
        User loginUser = userService.getLoginUser(httpRequest);
        
        // 查询任务并验证权限
        AIGenerationTask task = aiGenerationTaskService.lambdaQuery()
                .eq(AIGenerationTask::getTaskId, taskId)
                .eq(AIGenerationTask::getUserId, loginUser.getId())
                .one();
        
        ThrowUtils.throwIf(task == null, ErrorCode.NOT_FOUND_ERROR, "任务不存在");
        
        return ResultUtils.success(task);
    }

    /**
     * 批量生成图片
     *
     * @param request 批量生成请求
     * @param httpRequest HTTP请求
     * @return 任务ID列表
     */
    @PostMapping("/batch")
    public BaseResponse<List<String>> batchGenerate(@RequestBody BatchGenerationRequest request,
                                                  HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getPrompts() == null || request.getPrompts().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "提示词列表不能为空");
        ThrowUtils.throwIf(request.getPrompts().size() > 10, 
            ErrorCode.PARAMS_ERROR, "批量生成数量不能超过10个");
        
        User loginUser = userService.getLoginUser(httpRequest);
        AIGenerationConfig config = request.getConfig() != null ? request.getConfig() : new AIGenerationConfig();
        
        List<String> taskIds = aiGenerationTaskService.batchGenerate(request.getPrompts(), config, loginUser.getId());
        
        return ResultUtils.success(taskIds);
    }

    /**
     * 取消生成任务
     *
     * @param taskId 任务ID
     * @param httpRequest HTTP请求
     * @return 是否成功
     */
    @PostMapping("/cancel/{taskId}")
    public BaseResponse<Boolean> cancelTask(@PathVariable String taskId,
                                          HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(taskId == null || taskId.trim().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "任务ID不能为空");
        
        User loginUser = userService.getLoginUser(httpRequest);
        boolean success = aiGenerationTaskService.cancelTask(taskId, loginUser.getId());
        
        return ResultUtils.success(success);
    }

    /**
     * 重新生成
     *
     * @param taskId 原任务ID
     * @param httpRequest HTTP请求
     * @return 新任务ID
     */
    @PostMapping("/regenerate/{taskId}")
    public BaseResponse<String> regenerate(@PathVariable String taskId,
                                         HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(taskId == null || taskId.trim().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "任务ID不能为空");
        
        User loginUser = userService.getLoginUser(httpRequest);
        String newTaskId = aiGenerationTaskService.regenerate(taskId, loginUser.getId());
        
        ThrowUtils.throwIf(newTaskId == null, ErrorCode.OPERATION_ERROR, "重新生成失败");
        
        return ResultUtils.success(newTaskId);
    }

    /**
     * 获取用户统计数据
     *
     * @param httpRequest HTTP请求
     * @return 统计数据
     */
    @GetMapping("/statistics")
    public BaseResponse<Map<String, Object>> getUserStatistics(HttpServletRequest httpRequest) {
        User loginUser = userService.getLoginUser(httpRequest);
        Map<String, Object> statistics = aiGenerationTaskService.getUserStatistics(loginUser.getId());
        
        return ResultUtils.success(statistics);
    }

    /**
     * 获取热门提示词
     *
     * @param limit 限制数量
     * @return 热门提示词列表
     */
    @GetMapping("/popular-prompts")
    public BaseResponse<List<Map<String, Object>>> getPopularPrompts(@RequestParam(defaultValue = "10") Integer limit) {
        List<Map<String, Object>> popularPrompts = aiGenerationTaskService.getPopularPrompts(limit);
        
        return ResultUtils.success(popularPrompts);
    }

    /**
     * 获取推荐配置
     *
     * @param httpRequest HTTP请求
     * @return 推荐配置
     */
    @GetMapping("/recommended-config")
    public BaseResponse<AIGenerationConfig> getRecommendedConfig(HttpServletRequest httpRequest) {
        User loginUser = userService.getLoginUser(httpRequest);
        AIGenerationConfig config = aiGenerationTaskService.getRecommendedConfig(loginUser.getId());
        
        return ResultUtils.success(config);
    }

    /**
     * 获取生成历史
     *
     * @param page 页码
     * @param size 页大小
     * @param httpRequest HTTP请求
     * @return 历史记录
     */
    @GetMapping("/history")
    public BaseResponse<Map<String, Object>> getGenerationHistory(@RequestParam(defaultValue = "1") Integer page,
                                                                @RequestParam(defaultValue = "20") Integer size,
                                                                HttpServletRequest httpRequest) {
        User loginUser = userService.getLoginUser(httpRequest);
        Map<String, Object> history = aiGenerationTaskService.getGenerationHistory(loginUser.getId(), page, size);
        
        return ResultUtils.success(history);
    }

    /**
     * 导出生成结果
     *
     * @param request 导出请求
     * @param httpRequest HTTP请求
     * @return 导出文件URL
     */
    @PostMapping("/export")
    public BaseResponse<String> exportResults(@RequestBody ExportRequest request,
                                            HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getTaskIds() == null || request.getTaskIds().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "任务ID列表不能为空");
        
        User loginUser = userService.getLoginUser(httpRequest);
        String format = request.getFormat() != null ? request.getFormat() : "zip";
        
        String exportUrl = aiGenerationTaskService.exportResults(request.getTaskIds(), loginUser.getId(), format);
        
        return ResultUtils.success(exportUrl);
    }

    /**
     * 获取待处理任务（管理员）
     *
     * @param limit 限制数量
     * @return 待处理任务列表
     */
    @GetMapping("/pending-tasks")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<AIGenerationTask>> getPendingTasks(@RequestParam(defaultValue = "10") Integer limit) {
        List<AIGenerationTask> tasks = aiGenerationTaskService.getPendingTasks(limit);
        
        return ResultUtils.success(tasks);
    }

    // ==================== 请求DTO类 ====================

    /**
     * 生成请求
     */
    public static class GenerationRequest {
        private String prompt;
        private AIGenerationConfig config;
        
        public String getPrompt() { return prompt; }
        public void setPrompt(String prompt) { this.prompt = prompt; }
        public AIGenerationConfig getConfig() { return config; }
        public void setConfig(AIGenerationConfig config) { this.config = config; }
    }

    /**
     * 批量生成请求
     */
    public static class BatchGenerationRequest {
        private List<String> prompts;
        private AIGenerationConfig config;
        
        public List<String> getPrompts() { return prompts; }
        public void setPrompts(List<String> prompts) { this.prompts = prompts; }
        public AIGenerationConfig getConfig() { return config; }
        public void setConfig(AIGenerationConfig config) { this.config = config; }
    }

    /**
     * 导出请求
     */
    public static class ExportRequest {
        private List<String> taskIds;
        private String format;
        
        public List<String> getTaskIds() { return taskIds; }
        public void setTaskIds(List<String> taskIds) { this.taskIds = taskIds; }
        public String getFormat() { return format; }
        public void setFormat(String format) { this.format = format; }
    }
}
